/**
 * Vue 3 转场动画指令
 * 使用方法: v-motion:targetId="isActive"
 */
export default {
    // Vue 3: beforeMount 替代 Vue 2 的 bind
    beforeMount(el, binding) {
        // 存储点击处理函数到元素上,方便后续清理
        el._motionClickHandler = () => {
            const cutto = document.getElementById(binding.arg)
            if (!cutto) {
                console.warn(`Motion directive: Element with id "${binding.arg}" not found`)
                return
            }

            const initStyle = `display:none;position:absolute;left:0;right:0;height:0;z-index:1;transition:all 200ms;overflow:hidden;`

            if (binding.value) {
                // 展开动画
                const motionActive = `display:block;top:${el.offsetTop}px;height:${el.offsetHeight}px`
                cutto.setAttribute('motion-enter', motionActive)
                cutto.style = initStyle + motionActive

                setTimeout(() => {
                    cutto.style = initStyle + 'display:block;top:0;height:100%;'
                }, 30)

                setTimeout(() => {
                    cutto.style.overflowY = 'auto'
                }, 200)
            } else {
                // 收起动画
                cutto.scrollTop = 0
                const enterStyle = cutto.getAttribute('motion-enter')
                if (enterStyle) {
                    cutto.style = initStyle + enterStyle

                    setTimeout(() => {
                        cutto.style.opacity = 0
                        setTimeout(() => {
                            cutto.style = initStyle
                        }, 200)
                    }, 200)
                }
            }
        }

        el.addEventListener('click', el._motionClickHandler)
    },

    // Vue 3: mounted 替代 Vue 2 的 inserted
    mounted(el, binding) {
        // 设置父元素定位
        if (el.parentNode) {
            el.parentNode.style.position = 'relative'
        }

        // 初始化目标元素样式
        const targetElement = document.getElementById(binding.arg)
        if (targetElement) {
            targetElement.style = `display:none; position:absolute; left:0; right:0; height:0; z-index:1; transition:all 200ms; overflow:hidden;`
        } else {
            console.warn(`Motion directive: Element with id "${binding.arg}" not found`)
        }
    },

    // Vue 3: unmounted 替代 Vue 2 的 unbind (清理事件监听器)
    unmounted(el) {
        if (el._motionClickHandler) {
            el.removeEventListener('click', el._motionClickHandler)
            delete el._motionClickHandler
        }
    }
}